package cn.lbf.stuniversity.utils;

import java.lang.reflect.Field;

public class MyFieldUtils {
        public static <T> T getFieldValue(Object bean, String fieldName, Class<T> typeName) {
            try {
                Class beanClass = bean.getClass();
                Field[] fs = beanClass.getDeclaredFields();

                for (int i = 0; i < fs.length; i++) {
                    Field f = fs[i];
                    f.setAccessible(true); //设置些属性是可以访问的
                    if (fieldName.equals(f.getName())) {
                        return (T) f.get(bean);
                    }
                }
                return null;
            } catch (IllegalAccessException e) {
                System.out.println(String.format("出错:实体类%s没有%s类型的%s属性字段!", bean.getClass(), typeName.getSimpleName(), fieldName));
                throw new RuntimeException(e);
            }
        }

        public static void setFieldValue(Object bean, String fieldName, Object value) {
            try {
                Class beanClass = bean.getClass();
                Field[] fs = beanClass.getDeclaredFields();
                for (int i = 0; i < fs.length; i++) {
                    Field f = fs[i];
                    f.setAccessible(true); //设置些属性是可以访问的
                    if (fieldName.equals(f.getName())) {
                        f.set(bean, value);
                    }
                }
            } catch (IllegalAccessException e) {
                System.out.println(String.format("出错:实体类%s没有%s属性字段!", bean.getClass(), fieldName));
                throw new RuntimeException(e);
            }
        }

        public static Object setClassDateRange(Object obj) {
            String beginDate = getFieldValue(obj, "beginDate", String.class);
            String endDate = getFieldValue(obj, "endDate", String.class);
            if (StringUtils.isNotEmpty(beginDate) && StringUtils.isNotEmpty(endDate)) {
                //开始、结束日期不为空
                if (beginDate.equals(endDate)) {
                    setFieldValue(obj, "classDateRange", beginDate.replaceAll("-", "/"));
//                courseDetailVo.setClassDateRange(courseDetailVo.getBeginDate().replaceAll("-", "/")); //只有一个日期
                } else {
                    setFieldValue(obj, "classDateRange", beginDate.replaceAll("-", "/") + "-" + endDate.replaceAll("-", "/"));
//                courseDetailVo.setClassDateRange(courseDetailVo.getBeginDate().replaceAll("-", "/") + courseDetailVo.getEndDate().replaceAll("-", "/"));
                }
            } else {
                //开始、结束日期为空
                setFieldValue(obj, "classDateRange", "");
//            courseDetailVo.setClassDateRange("");
            }
            return obj;
        }
}
